package com.apache.portal.common.util;

import java.io.*;


import com.apache.uct.common.ToolsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对文件的删除、剪切、移动和创建文件夹操作
 * 
 * @author Hou Dayu
 */
public class FileOperate {

	private static Logger log = LoggerFactory.getLogger(FileOperate.class);
	private static FileOperate instance = null;

	private FileOperate() {

	}

	public synchronized static FileOperate getInstance() {
		if (null == instance)
			instance = new FileOperate();
		return instance;
	}

	/**
	 * 检查文件或文件夹是否存在
	 * 
	 * @param folderPath  文件或文件夹路径
	 * @return            true为存在，false不存在
	 */
	public boolean checkFolder(String folderPath) {
		boolean result = false;
		if (ToolsUtil.isNotNull(folderPath)) {
			File newFilePath = new File(folderPath);
			result = newFilePath.exists();
		}
		return result;
	}

	/**
	 * 新建目录操作
	 * 
	 * @param folderPath 文件夹路径
	 */
	public boolean newCreateFolder(String folderPath) {
		boolean result = false;
		try {
			if (ToolsUtil.isNotNull(folderPath)) {
				folderPath = folderPath.replace("//", "/");
				File newFilePath = new File(folderPath);
				if (!newFilePath.exists()) {
					result = newFilePath.mkdirs();
				}
				//				else {
				//					throw new BusinessException("已存在同名文件夹，文件[" + folderPath + "]目录不用再创建!");
				//				}
			}
		} catch (Exception e) {
			log.error("新建目录操作出错ERROR KEY:" + e.getMessage());
		}
		return result;
	}

	/**
	 * 创建新的文件
	 * 
	 * @param filePathAndName 文件名称
	 * @param fileContent     文件内容
	 */
	public boolean newCreateFile(String filePathAndName, String fileContent) {
		boolean result = false;
		try {
			if (ToolsUtil.isNotNull(filePathAndName)) {
				filePathAndName = filePathAndName.replace("//", "/");
				File newFilePath = new File(filePathAndName);
				if (!newFilePath.exists()) {
					newFilePath.createNewFile();
				}
				FileOutputStream fo = new FileOutputStream(filePathAndName);//"content_page.js");
				OutputStreamWriter osw = new OutputStreamWriter(fo, "UTF-8");
				PrintWriter out1 = new PrintWriter(osw);
				out1.println(fileContent);
				out1.close();
				osw.close();
				fo.close();
				result = true;
				log.info("创建文件:"+filePathAndName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("新建文件操作出错ERROR KEY:" + e.getMessage());
		}
		return result;
	}

	/**
	  * description: 获取指定文件夹下的文件列表
	  * @param filePath 文件夹路径
	  * @return
	 */
	public File[] getFileList(String filePath) {
		File file = new File(filePath);
		File flist[] = file.listFiles();
		return flist;
	}

	/**
	 * 返回文件名
	 *
	 * @param fileName
	 * @return
	 */
	public String getFileName(String fileName) {
		File file = new File(fileName);
		return file.getName();
	}

	/**
	 * 格式化文件路径
	 *
	 * @param path 文件路径
	 * @return
	 */
	public String formatFilePath(String path) {
		if (ToolsUtil.isNull(path))
			return "";
		path = path.replace("\\", "/");
		path = path.replace("\\\\", "/");
		return path.replace("//", "/");
	}

	/**
	 * 首字母小写
	 * @param str
	 * @return
	 */
	public String toLowerFirst(String str) {
		if (ToolsUtil.isNull(str))
			return "";
		StringBuffer sb = new StringBuffer();
		sb.append(str.substring(0, 1).toLowerCase() + str.substring(1));
		return sb.toString();
	}

	/**
	 * 首字母大写
	 * @param str
	 * @return
	 */
	public String toUpperFirst(String str) {
		if (ToolsUtil.isNull(str))
			return "";
		String names[] = str.split("_");
		StringBuffer sb = new StringBuffer();
		if (names.length < 2) {
			sb.append(names[0].substring(0, 1).toUpperCase() + names[0].substring(1));
		} else {
			for (int i = 0; i < names.length; i++) {
				sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1));
			}
		}
		return sb.toString();
	}

	/**
	 * 属性值生成,符合骆驼命名
	 * @param str
	 * @return
	 */
	public String toCamelNamed(String str) {
		if (ToolsUtil.isNull(str))
			return "";
		String names[] = str.split("_");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < names.length; i++) {
			if (i == 0) {
				sb.append(names[i].toLowerCase());
			} else {
				sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}

	/**
	 * 取得文件扩展名
	 * @param name
	 * @return String
	 */
	public String getExtension(String name) {
		int i = name.lastIndexOf('.');
		if (i >= 0)
			return name.substring(i + 1).toLowerCase();
		else
			return "";
	}

	/**
	 * 复制文件夹
	 * @param sourcePath
	 * @param newPath
	 * @throws IOException
	 */
	public void copyDir(String sourcePath, String newPath) {
		File file = new File(sourcePath);
		if(file.exists()){
			String[] filePath = file.list();

			if (!(new File(newPath)).exists()) {
				(new File(newPath)).mkdir();
			}

			for (int i = 0; i < filePath.length; i++) {
				String sourceFilePath = sourcePath + file.separator + filePath[i];
//			log.info("copying website resources  --> "+sourceFilePath);
				if ((new File(sourceFilePath)).isDirectory()) {
					copyDir(sourceFilePath, newPath  + file.separator + filePath[i]);
				}

				if (new File(sourceFilePath).isFile()) {
					copyFile(sourceFilePath, newPath + file.separator + filePath[i]);
				}

			}
		}else{
			log.info("copying path --> "+file.getPath());
			log.info("copying website --> "+sourcePath+"目录不存在，无需复制！");
		}
	}

	/**
	 * 复制文件
	 * @param oldPath
	 * @param newPath
	 * @throws IOException
	 */
	public void copyFile(String oldPath, String newPath){
		File oldFile = new File(oldPath);
		File file = new File(newPath);
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(oldFile);
			out = new FileOutputStream(file);

			byte[] buffer=new byte[2097152];
			int readByte = 0;
			while((readByte = in.read(buffer)) != -1){
                out.write(buffer, 0, readByte);
            }
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}

	}

	public static void main(String[] args) {
		String sourcePath="E:\\website2\\tiantang\\wcm\\tiantang";
		String newPath="E:\\website2\\tiantang\\wcm";
		FileOperate.getInstance().copyDir(sourcePath,newPath);
	}
}
